package stack;

import java.util.Stack;

//字符串解码
public class DecodeString {
    public String code(String ss) {
        Stack<StringBuffer> stringStack = new Stack<>();
        stringStack.push(new StringBuffer());
        Stack<Integer> intStack = new Stack<>();

        char[] s = ss.toCharArray();
        int n = ss.length();
        for (int i = 0; i < n;){
            //是数字
            if (s[i] >= '0' && s[i] <= '9'){
                //提取出一个完整的原神
                int tmp = 0;
                while (i < n && s[i] >= '0' && s[i] <= '9'){
                    tmp = tmp * 10 + (s[i] - '0');
                    i++;
                }
                intStack.push(tmp);
            }else if (s[i] == '['){
                i++;
                StringBuffer tmp = new StringBuffer();
                while (i < n && s[i] >= 'a' && s[i] <= 'z'){
                    tmp.append(s[i]);
                    i++;
                }
                stringStack.push(tmp);
            }else if (s[i] == ']'){
                //解析元素
                int count = intStack.pop();  //次数
                StringBuffer tmp = stringStack.pop();

                while (count-- != 0){
                    stringStack.peek().append(tmp);
                }
                i++;
            }else {
                StringBuffer tmp = new StringBuffer();
                while (i < n && s[i] >= 'a' && s[i] <= 'z'){
                    tmp.append(s[i]);
                    i++;
                }
                stringStack.peek().append(tmp);
            }
        }

        return stringStack.peek().toString();
    }
}
